import * as echarts from 'echarts';
import {ref, reactive} from 'vue';
import {studentTeacher, studentDrop, studentGather, schoolTree} from "@/api/student";
import router from '@/router'
import {useStorage} from "@/hooks/web/useStorage";

export const useCommon = () => {
    let loading = ref(false)
    let chartRef = ref('')
    const {getStorage} = useStorage()
    let marketing = ref('')
    let pageData = reactive({
        currentPage: 1,
        pageSize: 20,
        total: 0,
    })

    /**
     * 节流函数
     * @param fn
     * @param time
     * @returns
     */
    const throttle = (fn, time) => {
        let timeout;
        return () => {
            if (!timeout) {  //自动类型转换
                timeout = setTimeout(() => {  //setTimeout 延迟执行
                    //先清除之前的任务
                    fn.apply()
                    timeout = undefined;
                }, time)
            }
        }
    }

    /**
     * 防抖函数
     * @param func
     * @param wait
     * @returns
     */
    const debounce = (func, wait) => {
        //定时器变量
        var timeout;
        return function () {
            //每次触发scrolle，先清除定时器
            clearTimeout(timeout);
            //指定多少秒后触发事件操作handler
            timeout = setTimeout(func, wait);
        };
    };


    /**
     * 重置echarts图标尺寸
     */
    const createFigure = () => {
        var chartDom = document.getElementById(chartRef.value)!;
        var myChart = echarts.init(chartDom);
        myChart.resize()
    }

    let searchForm = reactive({
        channel_id: '',    //客户机构
        school: '',       //学校
        realname: '',     //学生姓名
        type: '',         //
        ruxue: '',        //入学时间
        yixiang: '',      //学生意向
        status: '',       //当前状态
        laidian: '',      //联系方式
        zixun: '',        //招生老师
        luqu_status: '',  //录取状态
        st_time: '',      //开始时间
        end_time: '',     //结束时间
        callback: '',     //回访状态
        laiyuan: '',      //学生来源
        statusMultiple: '',//当前状态多选
        time: '',
        tab: '1',
    })

    const mobileShow = ref(false)
    let optionsBox = reactive({
        xueli_list: [],     //学历
        laiyuan_list: [],   //学生来源
        ruxue_list: [],     //入学时间
        status_list: [],    //当前状态,
        yixiang_list: [],   //意向类型
        sex_list: [{name: '男', value: '1'}, {name: '女', value: '0'}],        //性别
        teacher_list: [],   //下拉老师选项
        school_list: [],    //学校下拉数据
        project_list: [],   //项目下拉数据
        zy_list: [],        //专业下拉数据
        other_list: [],     //其他语言,
        waiyu_nengli_list: [],
        zhiye_list: [],     //职业
        zhiye_leixing: [],   //职业类型下拉数据
        status_id_list: [], //当前状态
        topik_list: [],     //topik等级
        certificate_list: [{name: '双证', value: '双证'}, {name: '单证', value: '单证'}],
    })

    let studentForm = reactive({
        gaokao: '',           //高考总分
        yingyu: '',           //英语成绩
        baokao: '',           //报考信息
        other_yuyan: '',      //其他语言成绩
        other_yuyan_fen: '',  //其他语言分数
        shouyao: '1',         //首要号码
        created_time: '',     //系统时间
        created_change: 0,    //是否更改系统时间
        teacher_id: '',       //招生老师
        hezuoren: '',         //合作人
        realname: '',         //姓名
        sex: '',              //性别
        xueli: '',            //学历
        laidian: '',          //来电号码
        modi2: '',            //登记号码
        weixin_name: '',      //微信名
        weixin: '',           //微信号
        idnum: '',            //身份证号码
        biye: '',             //毕业学校
        zhiye_leixing: '',    //职业类型
        laiyuan: '',          //学生来源
        laiyuan_xiangqing: '',//来源详情
        project_id: '',       //申请项目
        zy1: '',              //申请专业
        ruxue: '',            //入学时间
        yixiang: '',          //意向类型
        status: '',           //当前状态
        desc: '',             //首咨信息
        next_visit_time: '',  //下次回访时间
        school_id: '',        //学校
        email: '',              //电子邮箱
        waiyu_nengli: '',        //外语能力
        topik: '',               //topik成绩
        certificate: '',         //证书
        interview_time: '',      //面试时间
        visitation_time: '',     //预毕业时间
        school_id_name:'',
        school_id_form:'',
        zy_id_name:'',
        zy_id_form:'',
        waiyu_fenshu:'',       //其他语言分数
        graduation:'',         //预毕业时间
    })

    let projectTree = ref([])
    const getProjectTree = async (level) => {
        let res;
        if (level) {
            res = await schoolTree({})
        } else {
            res = await schoolTree({level: 2})
        }

        console.log(res)
        if (res) {
            projectTree.value = res.data
        }
    }


    const handleChange = (value) => {
        getTeacher({type: 'pro', school: value})
    }

    const handleTime = async () => {
    }

    let teacherOptions = ref([])
    let relTeacherOpt = ref([])

    //获取招生老师
    const getTeacher = async (params) => {
        let res = await studentTeacher(params)
        if (res) {
            let options = []
            for (const resKey in res.data.teacher_list) {
                options.push({name: res.data.teacher_list[resKey], id: resKey})
            }

            if (params) {
                relTeacherOpt.value = options
            } else {
                teacherOptions.value = options
                optionsBox.teacher_list = options
            }
        }
    }

    //获取渠道下拉数据
    let channelOptions = ref([])
    const getChannel = async () => {
        // let res = await channelListBy()
        // if (res) {
        //     channelOptions.value = res.data
        //     optionsBox.channel_list = res.data
        // }
    }

    const onSourceChange = (e) => {
        console.log(e);
        if (e !== '渠道') {
            studentForm.channel_id = ''
        }
    }

    //获取学校,项目,专业下拉数据
    let schoolOptions = reactive([])
    let degreeOptions = ref([])
    let specialtyOptions = ref([])
    const fetchDataBox = async (type, e) => {
        let params = {
            school_id: studentForm.school_id || e,
            type: type,
            pro_id: studentForm.project_id
        }
        let res = await studentDrop(params)
        if (res) {
            if (type === 'school') {
                schoolOptions= Object.assign(schoolOptions,res.data)
                optionsBox.school_list = res.data
            } else if (type === 'project') {
                degreeOptions.value = res.data
                optionsBox.project_list = res.data
            } else if (type === 'zy') {
                specialtyOptions.value = res.data
                optionsBox.zy_list = res.data
            }
        }
    }

    /**
     * 获取下拉数据的集合
     * @returns {Promise<void>}
     */
    const gatherOptions = async () => {
        let res = await studentGather({})
        if (res) {
            //当前学历
            for (const resKey in res.data.xueli_list) {
                optionsBox.xueli_list.push({name: res.data.xueli_list[resKey], value: resKey})
            }
            //学生来源
            for (const resKey in res.data.laiyuan_list) {
                optionsBox.laiyuan_list.push({name: res.data.laiyuan_list[resKey], value: resKey})
            }
            //入学时间
            for (const resKey in res.data.ruxue_list) {
                optionsBox.ruxue_list.push({name: res.data.ruxue_list[resKey], value: resKey})
            }
            //其他语言
            for (const resKey in res.data.other_list) {
                optionsBox.waiyu_nengli_list.push({name: res.data.other_list[resKey], value: resKey})
            }
            //职业
            for (const resKey in res.data.zhiye_list) {
                optionsBox.zhiye_list.push({name: res.data.zhiye_list[resKey], value: resKey})
            }
            //当前状态
            for (const resKey in res.data.status_list) {
                optionsBox.status_list.push({name: res.data.status_list[resKey], value: resKey})
            }
            //topik等级
            for (const resKey in res.data.topik_list) {
                optionsBox.topik_list.push({name: res.data.topik_list[resKey], value: resKey})
            }
            //意向类型
            for (const resKey in res.data.yixiang_list) {
                optionsBox.yixiang_list.push({name: res.data.yixiang_list[resKey], value: resKey})
            }
        }
    }

    const isMarketing = () => {
        let userInfo = getStorage('userInfo')
        let role = userInfo.role_id
        role = role.split(',')
        marketing.value = role.find(item => {
            return item == 4
        })
    }

    watch(teacherOptions, (value) => {
        isMarketing()
        if (marketing.value) return
        if (router.currentRoute._value.path !== '/commonality/index') {
            if (value.length === 1) {
                studentForm.teacher_id = value[0].id
                searchForm.zixun = value[0].name
                console.log('zixun', searchForm.zixun);
            }
        }

    }, {immediate: true, deep: true})

    return {
        loading,
        channelOptions, //渠道下拉数据
        pageData,      //分页参数
        schoolOptions, //学校下拉数据
        degreeOptions, //项目下拉数据
        specialtyOptions, //专业下拉数据
        teacherOptions,
        optionsBox,
        mobileShow,
        searchForm,
        chartRef,
        studentForm,
        projectTree,
        relTeacherOpt, //公海绑定老师选择项
        marketing,
        getProjectTree, //获取院校项目树形数据
        gatherOptions,
        fetchDataBox,
        getTeacher,
        handleTime,
        handleChange,
        throttle,
        createFigure,
        debounce,
        getChannel,
        onSourceChange,
        isMarketing,
    }
}